package com.lzx.iteam.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;
import com.lzx.iteam.R;
import com.lzx.iteam.net.AsynHttpClient;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.List;

import static com.lzx.iteam.AlbumActivity.bitmap;

/**
 * Created by .
 */
public class ShareUtil {
    private static ShareUtil mShareUtil;
    private Activity mContext;
    private IWXAPI wxApi=null;

    public static String APP_ID = "wx75dd52bb816fcf7c";
    public static String APP_SCREAT = "73528c740917290647270ba183f26560";


    private ShareUtil(Activity context){
        this.mContext = context;
//        this.mController = UMServiceFactory.getUMSocialService("com.umeng.share");
        wxApi = WXAPIFactory.createWXAPI(context, APP_ID);
        wxApi.registerApp(APP_ID);
    }

    public synchronized static ShareUtil getInstance(Activity context) {
        if (mShareUtil == null) {
            mShareUtil = new ShareUtil(context);
        }
        return mShareUtil;
    }


    // TODO  微信图文分享时，必须加分享链接，否则点击会进入友盟的界面
    // TODO  微信分享支持图文分享、纯图片及纯文字分享，其中图文分享点击会跳转到设置的URL，纯图片分享可以点击查看大图
    // TODO  图文分享方法参考上文，纯图片分享方法只需要去掉文本内容设置即可
    // TODO  纯文本分享方法与纯图片类似，去掉分享图片即可

    /**
     * 分享到微信
     * method:  1,是详情页分享联系方式   2,是我的页面分享下载地址 3,分享整个事件到微信
     */
    public void shareToWx(String title,String shareText,String url, int method,final Bitmap shareImage){

        if (!isWeixinAvilible(mContext)){
            Toast.makeText(mContext, "分享失败，请先安装微信", Toast.LENGTH_SHORT).show();
            return;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        if (method == 3){
            webpage.webpageUrl = url;
        } else{
            webpage.webpageUrl = AsynHttpClient.HTTP_TEAM_DOWNLOAD;
        }

        WXMediaMessage msg = new WXMediaMessage();
        if (!StringUtil.isEmpty(title)){
            msg.title = title;
        }
        if (!StringUtil.isEmpty(shareText)){
            msg.description = shareText;
        }
        if (method == 2 || method == 3){
            msg.setThumbImage(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.team_icon));
        }
        msg.mediaObject = webpage;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        wxApi.sendReq(req);


        /*UMWXHandler wxHandler = new UMWXHandler(mContext,APP_ID,APP_SCREAT);
        wxHandler.addToSocialSDK();
        WeiXinShareContent weixinContent = new WeiXinShareContent();
        if (!StringUtil.isEmpty(title)){
            weixinContent.setTitle(title);
        }
        if(shareText != null){
            weixinContent.setShareContent(shareText);
        }else{
            weixinContent.setShareContent("");
        }
        // 分享链接
        if ( method == 3){
            weixinContent.setTargetUrl(url);
        }else{
            weixinContent.setTargetUrl(AsynHttpClient.HTTP_TEAM_DOWNLOAD);
        }
        if (method == 2 || method == 3){
            weixinContent.setShareImage(new UMImage(mContext, R.drawable.team_icon));
        }
        mController.setShareMedia(weixinContent);
        mController.directShare(mContext, SHARE_MEDIA.WEIXIN, new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, SocializeEntity socializeEntity) {
                if (shareImage != null && !shareImage.isRecycled()) {
                    Log.i("weixin", "bitmap");
                    shareImage.recycle();
                }
            }
        });*/
    }

    /**
     * 分享到朋友圈
     *
     * from:  1,我的页面分享下载地址   2，分享事件到朋友圈
     *
     */
    public void shareToWxCircle(String shareText, String url, final Bitmap shareImage){

        if (!isWeixinAvilible(mContext)){
            Toast.makeText(mContext, "分享失败，请先安装微信", Toast.LENGTH_SHORT).show();
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        if (!StringUtil.isEmpty(url)){
            webpage.webpageUrl = url;
        }  else{
            webpage.webpageUrl = AsynHttpClient.HTTP_TEAM_DOWNLOAD;
        }

        WXMediaMessage msg = new WXMediaMessage();
        if (!StringUtil.isEmpty(shareText)){
            msg.title = shareText;
//            msg.description = shareText;
        }
        if (shareImage == null){
            msg.setThumbImage(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.team_icon));
        } else{
            msg.setThumbImage(bitmap);
        }
        msg.mediaObject = webpage;

        SendMessageToWX.Req req = new SendMessageToWX.Req();

        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;

        wxApi.sendReq(req);


        /*UMWXHandler wxCircleHandler = new UMWXHandler(mContext,APP_ID,APP_SCREAT);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
        CircleShareContent circleMedia = new CircleShareContent();
        if(shareText != null){
            circleMedia.setShareContent(shareText);
        }else{
            circleMedia.setShareContent("");
        }
        circleMedia.setTitle(shareText);
        if(shareImage != null){
            circleMedia.setShareImage(new UMImage(mContext,shareImage));
        }else{
            circleMedia.setShareImage(new UMImage(mContext,R.drawable.team_icon));
        }
        if (url != null){
            circleMedia.setTargetUrl(url);
        }else{
            circleMedia.setTargetUrl(AsynHttpClient.HTTP_TEAM_DOWNLOAD);
        }
        mController.setShareMedia(circleMedia);
        mController.directShare(mContext, SHARE_MEDIA.WEIXIN_CIRCLE,new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, SocializeEntity socializeEntity) {
                if(shareImage != null && !shareImage.isRecycled()){
                    shareImage.recycle();
                }
            }
        });*/
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type
              + System.currentTimeMillis();
    }

    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 分享到QQ好友
     *
     * QQ好友分享支持纯文字、纯图片、图文分享及音乐等多媒体资源，
     * 其中 图文分享点击会跳转到预设URL，无法查看大图 ，需要点击查看大图需要设置为纯图片类型
     *//*
    public void shareToQQfriend(String shareText, final Bitmap shareImage){
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(mContext, Constants.QQ_APP_ID,
                Constants.QQ_APP_KEY);
        qqSsoHandler.addToSocialSDK();
        QQShareContent qqShareContent = new QQShareContent();
        if(shareText != null){
            qqShareContent.setShareContent(shareText);
        }else{
            qqShareContent.setShareContent("来自疯狂的兔子");
        }
        qqShareContent.setTitle("测试");
        if(shareImage != null){
            qqShareContent.setShareImage(new UMImage(mContext,shareImage));
        }else{
            qqShareContent.setShareImage(new UMImage(mContext, R.drawable.hdpi));
        }
        qqShareContent.setTargetUrl(Constants.SHARE_URL);
        mController.setShareMedia(qqShareContent);
        mController.directShare(mContext, SHARE_MEDIA.QQ,new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, SocializeEntity socializeEntity) {
                if(shareImage != null && !shareImage.isRecycled()){
                    shareImage.recycle();
                }
            }
        });
    }

    *//**
     * 分享到QQ空间
     *
     * Qzone分享只支持图文形式分享，并且点击图文消息会跳转到预设的链接，
     * 图文分享只展示缩略图，**无法查看大图**
     *//*
    public void shareToQQzone(String shareText, final Bitmap shareImage){
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(mContext, Constants.QQ_APP_ID,
                Constants.QQ_APP_KEY);
        qZoneSsoHandler.addToSocialSDK();
        QZoneShareContent qzone = new QZoneShareContent();
        if(shareText != null){
            qzone.setShareContent(shareText);
        }else{
            qzone.setShareContent("我的分享测试");
        }
        qzone.setTargetUrl(Constants.SHARE_URL);
        qzone.setTitle("测试");
        if(shareImage != null && !shareImage.isRecycled()){
            qzone.setShareImage(new UMImage(mContext,shareImage));
        }else{
            qzone.setShareImage(new UMImage(mContext,Constants.QQ_ZONE_PIC_URL));
        }
        mController.setShareMedia(qzone);
        mController.directShare(mContext, SHARE_MEDIA.QZONE,new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, SocializeEntity socializeEntity) {
                if(shareImage != null && !shareImage.isRecycled()){
                    shareImage.recycle();
                }
            }
        });

    }

    *//**
     * 分享到新浪微博
     *//*
    public void shareToSina(String shareText, final Bitmap shareImage){
        SinaSsoHandler sinaSsoHandler = new SinaSsoHandler();
        mController.getConfig().setSsoHandler(sinaSsoHandler);
        // TODO 设置授权回调网址，解决 21322 错误
        mController.getConfig().setSinaCallbackUrl(Constants.SHARE_URL);
        // 授权
        boolean isOath = OauthHelper.isAuthenticated(mContext, SHARE_MEDIA.SINA);
        SinaShareContent sina = new SinaShareContent();
        if(shareText != null && !"".equals(shareText)){
            sina.setShareContent(shareText);
        }else{
            sina.setShareContent("我的分享测试");
        }
        sina.setTargetUrl(Constants.SHARE_URL);
        sina.setTitle("测试");
        if(shareImage != null){
            sina.setShareImage(new UMImage(mContext,shareImage));
        }else{
            sina.setShareImage(new UMImage(mContext, Constants.QQ_ZONE_PIC_URL));
        }
        mController.setShareMedia(sina);
        mController.directShare(mContext, SHARE_MEDIA.SINA,new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, SocializeEntity socializeEntity) {
                if(shareImage != null && !shareImage.isRecycled()){
                    shareImage.recycle();
                }
            }
        });
    }

    *//**
     * 分享到腾讯微博
     *//*
    public void shareToTecentWeibo(String shareText, final Bitmap shareImage){
        TencentWBSsoHandler tencentWBSsoHandler = new TencentWBSsoHandler();
        mController.getConfig().setSsoHandler(tencentWBSsoHandler);
        TencentWbShareContent shareContent = new TencentWbShareContent();
        if(shareText != null && !"".equals(shareText)){
            shareContent.setShareContent(shareText);
        }else{
            shareContent.setShareContent("我的分享测试");
        }
        shareContent.setTargetUrl(Constants.SHARE_URL);
        shareContent.setTitle("测试");
        if(shareImage != null){
            shareContent.setShareImage(new UMImage(mContext,shareImage));
        }else{
            shareContent.setShareImage(new UMImage(mContext,Constants.QQ_ZONE_PIC_URL));
        }
        mController.setShareMedia(shareContent);
        mController.directShare(mContext, SHARE_MEDIA.TENCENT,new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, SocializeEntity socializeEntity) {
                if(shareImage != null && !shareImage.isRecycled()){
                    shareImage.recycle();
                }
            }
        });
    }

    *//**
     *
     *//*
    *//*public void shareToRenRen(String shareText, final Bitmap shareImage){
        mController.setAppWebSite(SHARE_MEDIA.RENREN, Constants.YAOYAN_WEB_URL);
        RenrenSsoHandler renrenSsoHandler = new RenrenSsoHandler(mContext,Constants.RENREN_APP_ID
                ,Constants.RENREN_API_KEY,Constants.RENREN_CECRET_KEY);
        mController.getConfig().setSsoHandler(renrenSsoHandler);
        RenrenShareContent renrenShareContent = new RenrenShareContent();
        if(shareText != null && !"".equals(shareText)){
            renrenShareContent.setShareContent(shareText);
        }else{
            renrenShareContent.setShareContent("摇出身边你不知道的事 -- 摇言www.yaoyan.so");
        }
        renrenShareContent.setTitle("测试");
        renrenShareContent.setTargetUrl(Constants.YAOYAN_WEB_URL);
        if(shareImage != null){
            renrenShareContent.setShareImage(new UMImage(mContext,shareImage));
        }else{
            renrenShareContent.setShareImage(new UMImage(mContext, Constants.QQ_ZONE_PIC_URL));
        }
        mController.setShareMedia(renrenShareContent);

        mController.directShare(mContext, SHARE_MEDIA.RENREN, new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, SocializeEntity socializeEntity) {
                if(shareImage != null && !shareImage.isRecycled()){
                    shareImage.recycle();
                }
            }
        });
    }*//*
    *//**
     * 通过短信分享
     *//*
    public void shareToSms(){
        Uri smsToUri = Uri.parse("smsto:");
        Intent sendIntent =  new Intent(Intent.ACTION_VIEW, smsToUri);
        sendIntent.putExtra( "sms_body" ,  "摇出身边你不知道的事 -- 摇言www.yaoyan.so" );
        sendIntent.setType( "vnd.android-dir/mms-sms" );
        mContext.startActivityForResult(sendIntent, 1002 );
    }

    *//**
     * 通过邮件分享
     *//*
    public void shareToMail(){
        Intent email =  new Intent(Intent.ACTION_SEND);
        email.setType( "plain/text" );
        String emailSubject ="摇言" ;
        email.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
        email.putExtra(Intent.EXTRA_TEXT, "摇出身边你不知道的事 -- 摇言www.yaoyan.so");
        mContext.startActivityForResult(Intent.createChooser(email, "请选择邮件发送软件"), 1001 );
    }*/



}
